package com.Server.DataBase;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

public class UuidTable {

	private static Logger _log = Logger.getLogger(UuidTable.class.getName());
	private static CopyOnWriteArrayList<String>_list = new CopyOnWriteArrayList<String>();
	
	private static UuidTable _instance ;
	
	public static UuidTable getInstance(){
		if(_instance == null){
			_instance = new UuidTable();
		}
		return _instance;
	}
	
	
	public void load(){
		Connection con = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {
			con = DatabaseFactoryLogin.get().getConnection();
			pstm = con.prepareStatement("SELECT * FROM UUID_BadList");
			rs = pstm.executeQuery();
			while (rs.next()) {
				_list.add(rs.getString(1));
			}
		} catch (final SQLException e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		} finally {
			SQLUtil.close(rs);
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
	}
	
	
	public void badUUID(final String uuid){
		_list.add(uuid);
		Connection con = null;
		PreparedStatement pstm = null;
		try {
			con = DatabaseFactoryLogin.get().getConnection();
			//TODO 追加判斷欄位host表,mask表
			pstm = con.prepareStatement("INSERT INTO UUID_BadList SET UUID=?");
			pstm.setString(1, uuid);
			pstm.execute();
		} catch (final SQLException e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		} finally {
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
	}
	
	public boolean chaekUUID(final String uuid){
		return _list.contains(uuid);
	}
	
	public void insertUUIDLog(final String ip , final String uuid){
		Connection con = null;
		PreparedStatement pstm = null;
		try {
			con = DatabaseFactoryLogin.get().getConnection();
			//TODO 追加判斷欄位host表,mask表
			pstm = con.prepareStatement("INSERT INTO UUID_Log SET TIME=? , IP=? , UUID=?");
			final Timestamp time = new Timestamp(System.currentTimeMillis());
			pstm.setTimestamp(1, time);
			pstm.setString(2, ip);
			pstm.setString(3, uuid);
			pstm.execute();
		} catch (final SQLException e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		} finally {
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
	}
	
}
